/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mb;

import beans.Mail;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import rn.MailRN;

/**
 *
 * @author Caio
 */
@ManagedBean(name="controllerMail")
@RequestScoped
public final class ControllerMail implements Serializable {
       
    @ManagedProperty(value="#{email}")
    private Mail email;

    private List<Mail> lista;
    
    public ControllerMail(){
        this.email = new Mail();
        this.lista = new ArrayList<Mail>();
    }
    
    public void limpar() {
        setEmail(new Mail());
    }

    ////////////////////////////////////////////////////////////////////////////   
        
    public List<Mail> getLista() {
        MailRN rn = new MailRN();
        this.lista = rn.listar();
        return this.lista;
    }    
       
    public void salvar(){
        MailRN rn = new MailRN();
        rn.salvar(this.email);
        FacesContext context = FacesContext.getCurrentInstance();            
        context.addMessage(null, new FacesMessage("Salvo com Sucesso"));
        limpar();
    }
        
    //Usado merge para recolocar um objeto que saiu do banco.... (Ex: como um update)
    //Evita o erro "a different object with the same identifier value was already associated with the session"
    public void merge(){
        MailRN rn = new MailRN();
        rn.merge(this.email);
        FacesContext context = FacesContext.getCurrentInstance();            
        context.addMessage(null, new FacesMessage("Alterado com Sucesso"));
    }

    public void preencherFormulario(){
        MailRN rn = new MailRN();
        List<Mail> list = getLista();
        if(!list.isEmpty()){
            this.email = rn.carregar(list.get(0).getId());
        }
    }
    
    ////////////////////////////////////////////////////////////////////////////
    
    public Mail getEmail() {
        return email;
    }

    public void setEmail(Mail email) {
        this.email = email;
    }
    
}
